﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using DBUtil;

namespace LIMS_QRCodeHtmlService
{
    public class QRCodeHtmlService : ServiceBase
    {
        public static Timer timer = new Timer();
        public static double interval = (1000 * 60) * 5; // 5 分钟 间隔执行


        /// <summary>
        /// 如果 间隔执行设定修改，则在下次执行更新间隔时间段
        /// </summary>
        private void RefashInterval()
        {
            ConfigurationManager.RefreshSection("connectionStrings");
            ConfigurationManager.RefreshSection("appSettings");
            interval = Utils.ConvertTo<double>(ConfigurationManager.AppSettings["Interval"], 1);
            timer.Interval = interval * (1000 * 60);
        }

        protected override void OnStart(string[] args)
        {
            RefashInterval();
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Start();
            LogUtils.LogInfo("二维码队列Html生成服务程序 启动", Developer.MJ);
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            RefashInterval();
            try
            {
                ExecBuilder();
            }
            catch (Exception ex)
            {
                LogUtils.LogError("二维码队列Html生成服务程序 异常", Developer.MJ, ex);
            }
        }

        protected override void OnStop()
        {
            LogUtils.LogInfo("二维码队列Html生成服务程序 停止", Developer.MJ);
        }

        protected override void OnShutdown()
        {
            LogUtils.LogInfo("二维码队列Html生成服务程序 关闭", Developer.MJ);
        }

        /// <summary>
        /// MySQL  查询待生成的html文件
        /// </summary>
        public void ExecBuilder()
        {
            DBSession db = new DBSession(DataBaseType.MySql);
            string select_sql = "SELECT  id,selectno,url,htmlcontent FROM sendreportqueue WHERE State=1 ORDER BY queueTime ASC LIMIT 30";
            DataTable data = db.QueryTable(select_sql, 300);
            string file_dir = ConfigurationManager.AppSettings["QRCode_BuildHtml_Dir"];
            if (!Directory.Exists(file_dir))
            {
                Directory.CreateDirectory(file_dir);
            }
            if (data != null && data.Rows.Count == 0)
            {
                System.Threading.Thread.Sleep(5000);
            }
            else
            {
                int res = -1;
                List<string> lstCodes = DBUtil.DBUtil.GetFirstCol<string>(data, "selectno");
                LogUtils.LogInfo("二维码生成html文件服务 开始生成", Developer.MJ, "本次生成共：" + data.Rows.Count + "条", lstCodes.ToArray());
                foreach (DataRow dr in data.Rows)
                {
                    string selectNo = string.Empty;
                    string url_html = string.Empty;
                    string idstr = string.Empty;
                    try
                    {
                        idstr = dr["id"].ToString();
                        selectNo = dr["SelectNo"].ToString();
                        url_html = dr["Url"].ToString();
                        string htmlContent = dr["HtmlContent"].ToString();
                        string qrdir = Path.GetDirectoryName(url_html).Replace("/", "\\").TrimStart('\\');
                        string html_file_dir = Path.Combine(file_dir, qrdir);
                        if (!Directory.Exists(html_file_dir))
                        {
                            Directory.CreateDirectory(html_file_dir);
                        }
                        string file_html = Path.Combine(html_file_dir, Path.GetFileName(url_html));
                        File.WriteAllText(file_html, htmlContent, System.Text.Encoding.UTF8);
                        Hashtable ht = new Hashtable();
                        ht.Add("Id", idstr);
                        ht.Add("State", 2);
                        ht.Add("FinishTime", DateTime.Now);                        
                        res = db.Update(ht, "sendreportqueue", "Id");
                        //睡上1秒，以便 同步数据时 能够有效区分时间段
                        System.Threading.Thread.Sleep(1000);
                        lstCodes.Add(selectNo);                        
                    }
                    catch (Exception ex)
                    {
                        LogUtils.LogInfo("二维码html生成服务出错", Developer.MJ, "报告编号:" + selectNo, "Url:" + url_html, ex, ex.InnerException);
                        continue;
                    }
                }
                LogUtils.LogInfo("二维码生成html文件服务 生成结束", Developer.MJ, "本次生成html文件完成！");
            }
        }
    }
}
